package com.gesonet.common.utils;

import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class StringUtils {
	
    private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
    
    public static final String EMPTY = "";

    private StringUtils() {
    }

    public static boolean isNotBlank(String str){
    	return org.apache.commons.lang3.StringUtils.isNotBlank(str);
    }
    
    public static int toInt(String str) {
        return toInt(str, -1);
    }

    public static int toInt(String str, int defaultValue) {
        if (isBlank(str)) {
            return defaultValue;
        }

        try {
            int returnValue = Integer.parseInt(str);
            return returnValue;
        } catch (Exception ex) {
            logger.error("", ex);
        }
        return defaultValue;
    }

    public static long toLong(String str) {
        return toLong(str, -1);
    }

    public static long toLong(String str, long defaultValue) {
        if (str == null) {
            return defaultValue;
        }
        try {
            long returnValue = Long.parseLong(str);
            return returnValue;
        } catch (Exception ex) {
            logger.error("", ex);
        }
        return defaultValue;
    }

    public static boolean isBlank(String _value) {
        return org.apache.commons.lang3.StringUtils.isBlank(_value);
    }

    /**
     * 字符串连接实现
     *
     * @param args
     * @return
     */
    public static String concat(Object... args) {
        if (args == null || args.length == 0) {
            return EMPTY;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Object arg : args) {
            stringBuilder.append(arg);
        }
        return stringBuilder.toString();
    }

    public static String concatWithSplit(String split, Object[] args) {
        if (args == null || args.length == 0) {
            return EMPTY;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Object arg : args) {
            stringBuilder.append(split).append(arg);
        }

        if (stringBuilder.length() > 0 && !StringUtils.isBlank(split)) {
            return stringBuilder.toString().substring(split.length());
        }
        return stringBuilder.toString();
    }

    /**
     * 仿c语言的sprintf实现
     *
     * @param format 字符串输出格式
     * @param args
     * @return
     */
    public static String sprintf(String format, Object... args) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        writer.printf(format, args);
        writer.close();
        return stringWriter.toString();
    }

    private static final String REGEXP_FORMAT_STRING = "(\\{\\d\\})";
    private static final Pattern pattern = Pattern.compile(REGEXP_FORMAT_STRING, Pattern.CASE_INSENSITIVE);

    /**
     * @param format aaaa{0}hello world{1}, welcome {0}
     * @param args
     * @return
     */
    public static String buildString(String format, Object... args) {
        Matcher matcher = pattern.matcher(format);
        String result = format;
        if (args == null) {
            return result;
        }
        while (matcher.find()) {
            String token = matcher.group();
            int idx = Integer.parseInt(token.substring(1, token.length() - 1));
            result = result.replace(token, args[idx] == null ? "" : args[idx].toString());
        }
        return result;
    }

    /**
     * 用于截取字符串
     * @param vname  标题名称
     * @param length 截取的长度
     * @return 截取后的字符串
     * @throws Exception
     */
    public static String nameSubstring(String vname, int length) {

        byte[] bytes = null;
        try {
            bytes = vname.getBytes("Unicode");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int n = 0; // 表示当前的字节数
        int i = 2; // 要截取的字节数，从第3个字节开始
        for (; i < bytes.length && n < length; i++) {
            // 奇数位置，如3、5、7等，为UCS2编码中两个字节的第二个字节
            if (i % 2 == 1) {
                n++; // 在UCS2第二个字节时n加1
            } else {
                // 当UCS2编码的第一个字节不等于0时，该UCS2字符为汉字，一个汉字算两个字节
                if (bytes[i] != 0) {
                    n++;
                }
            }
        }
        // 如果i为奇数时，处理成偶数
        if (i % 2 == 1) {

            // 该UCS2字符是汉字时，去掉这个截一半的汉字
            if (bytes[i - 1] != 0) {
                i = i - 1;
                // 该UCS2字符是字母或数字，则保留该字符
            } else {
                i = i + 1;
            }
        }

        String str = "";
        try {
            str = new String(bytes, 0, i, "Unicode");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return str;
    }


    /**
     * 检测ids中是否包含id
     *
     * @param id
     * @param ids
     * @return
     */
    public static boolean isContains(String id, String ids) {
        if (StringUtils.isBlank(id) || StringUtils.isBlank(ids)) {
            return false;
        }
        String[] idsArray = ids.split(",");
        for (String idstr : idsArray) {
            if (id.trim().equals(idstr.trim())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取字符串的字节长度
     *
     * @param s
     * @return
     */
    public static int getWordCount(String s) {
        int length = 0;
        for (int i = 0; i < s.length(); i++) {
            int ascii = Character.codePointAt(s, i);
            if (ascii >= 0 && ascii <= 255)
                length++;
            else
                length += 2;

        }
        return length;

    }

    public static String toString(Object obj, String[] property) {
        if (obj == null) {
            return null;
        }
        if (ArrayUtils.isEmpty(property)) {
            PropertyDescriptor[] props = new PropertyUtilsBean().getPropertyDescriptors(obj);
            if (props == null) {
                return obj.toString();
            }
            property = new String[props.length];
            for (int i = 0; i < props.length; i++) {
                property[i] = props[i].getName();
            }
        }
        StringBuilder sb = new StringBuilder();
        sb.append(obj.getClass().getName());
        sb.append("：{");
        List<String> propList = new ArrayList<String>(property.length);
        for (String prop : property) {
            try {
                propList.add(prop + "=" + BeanUtils.getProperty(obj, prop));
            } catch (Exception e) {
                logger.debug(e.getMessage(), e);
                propList.add(prop + "=NONE");
            }
        }
        sb.append(org.apache.commons.lang3.StringUtils.join(propList.iterator(), ","));
        sb.append("}");
        return sb.toString();
    }

    /**
     * 专辑名称去掉特殊符号。
     *
     * @param str
     * @return
     */
    public static String removeSpecial(String str) {
        if (str == null)
            return null;
        str = str.replaceAll("\\.", "");
        str = str.replaceAll("-", "");
        str = str.replaceAll("（", "");
        str = str.replaceAll("）", "");
        str = str.replaceAll("\\)", "");
        str = str.replaceAll("\\(", "");
        str = str.replaceAll("·", "");
        str = str.replaceAll(" ", "");
        str = str.replaceAll("　", "");
        return str;
    }
    
    public Integer[] string2IntAry(String str, String separatorChars,
			Integer[] defaultValue) {
		if (StringUtils.isBlank(str)) {
			return defaultValue;
		}
		String[] strAry = org.apache.commons.lang3.StringUtils.split(str, separatorChars);
		int len = strAry.length;
		Integer[] intAry = new Integer[len];
		for (int i = 0; i < len; i++) {
			intAry[i] = ObjectUtils.toInteger(strAry[i]);
		}
		return intAry;
	}

	public Long[] string2LongAry(String str, String separatorChars,
			Long[] defaultValue) {
		if (StringUtils.isBlank(str)) {
			return defaultValue;
		}
		String[] strAry = org.apache.commons.lang3.StringUtils.split(str, separatorChars);
		int len = strAry.length;
		Long[] longAry = new Long[len];
		for (int i = 0; i < len; i++) {
			longAry[i] = ObjectUtils.toLong(strAry[i]);
		}
		return longAry;
	}
	
	/***
	 * MD5加码 生成32位md5码
	 */
	public static String string2MD5(String inStr) {

		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = inStr.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 
     * 编码 
     * @param bstr 
     * @return String 
     */  
	@SuppressWarnings("restriction")
	public static String base64Encode(String str){  
    	return new sun.misc.BASE64Encoder().encode(str.getBytes());  
    }  
  
    /** 
     * 解码 
     * @param str 
     * @return string 
     * @throws IOException 
     */  
	@SuppressWarnings("restriction")
	public static String base64Decode(String str) throws IOException{  
        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();  
        byte[] bt = decoder.decodeBuffer(str);
        return new String(bt);
    }  
	
	/**
	 * 字符串反转
	 * @param str
	 * @return
	 */
	public static String reverse(String str){
		if(isNotBlank(str)){
			return new StringBuffer(str).toString();
		}else{
			return "";
		}
	}
	
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}
	
	public static boolean isMobilePhoneNum(String phone) {
		String str = "^(1)\\d{10}$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(phone);
		return m.matches();
	}

    public static void main(String[] args) throws Exception {
    	
    	System.out.println(isMobilePhoneNum("22000000000"));
//    	System.out.println(isEmail("421002198711301036"));
        //	System.out.println(concat(new Object[]{"\t", "hello", "\t", 4}));
//    	System.out.println(string2MD5("1"));
//    	String encode = base64Encode("用户中心");
//    	System.out.println(encode);
//    	System.out.println(base64Decode(encode));
    }



}